package com.ilibrary.db.dao;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Hibernate Dao基类
 * @author ZhongJiang
 * @param <T>
 * @param <PK>
 */
public abstract class MyBaseHibernateDao<T, PK extends Serializable> extends HibernateDaoSupport implements MyBaseDao<T, PK> {

	private Class<T> entityPOJO;
	public MyBaseHibernateDao() {
		Type type = getClass().getGenericSuperclass();
		Type trueType = ((java.lang.reflect.ParameterizedType) type).getActualTypeArguments()[0];
        this.entityPOJO = (Class<T>) trueType;
    }
	
	public PK add(T t) {
		return (PK)this.getHibernateTemplate().save(t);
	}

	public void update(T t) {
		this.getHibernateTemplate().update(t);
		
	}

	public void delete(PK id) {
		this.getHibernateTemplate().delete(findById(id));
		
	}

	public T findById(PK id) {
		return this.getHibernateTemplate().get(entityPOJO, id);
	}

	public List<T> findAll() {
		return this.getHibernateTemplate().loadAll(entityPOJO);
	}

	public List<T> findByExample(HashMap<String, Object> params) {
		
		DetachedCriteria detachedCrit = DetachedCriteria.forClass(entityPOJO);
		
		Iterator it = params.keySet().iterator();
		while(it.hasNext()){
			String key = (String)it.next();
			Object val = params.get(key);
			detachedCrit.add(Restrictions.eq(key,val));
		}
		List<T> rs = (List<T>)this.getHibernateTemplate().findByCriteria(detachedCrit);
		if(rs == null){
			rs = new ArrayList<T>();
		}
		return rs;
	}

}
